var gulp = require('gulp'),
sourcemaps = require('gulp-sourcemaps'),
minifycss = require('gulp-minify-css'),
autoprefixer = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
sass = require('gulp-sass'),
standard = require('gulp-standard'),
uglify = require('gulp-uglify'),
fs = require('fs'),
cached = require('gulp-cached'),
ejs = require('gulp-ejs'),
remember = require('gulp-remember'),
gutil = require('gulp-util'),
md5 = require('md5');

var srcStaticPath = 'src/static';
var distStaticPath = 'dist/static';
var env;
var browserSync = require('browser-sync');
var replace = require('gulp-replace');


// 删除dist文件夹以及其内容
gulp.task('clean', function () {
function deleteAll(path) {
  var files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function (file, index) {
      var curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) { // 删除文件夹
        deleteAll(curPath);
      } else { // 删除文件
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

deleteAll('dist');
});

//html复制
gulp.task('html', function () {
return gulp.src([
    'src/*/*.html'
  ])
  .pipe(ejs().on('error', gutil.log))
  .pipe(gulp.dest('dist'));
});

//图片复制（不复制将会替换的图片，只复制不变的图片）
gulp.task('img', function () {
return gulp.src(srcStaticPath + '/img/**/*')
  .pipe(gulp.dest(distStaticPath + '/img/'));
});

//swf复制
gulp.task('swf', function () {
return gulp.src(srcStaticPath + '/js/lib/*.swf')
  .pipe(gulp.dest(distStaticPath + '/js/lib/'));
});

//svg复制
gulp.task('svg', function () {
return gulp.src(srcStaticPath + '/svg/**/*.svg')
  .pipe(gulp.dest('dist/svg'));
});

//字体文件复制
gulp.task('font', function () {
return gulp.src(srcStaticPath + '/font/*')
  .pipe(gulp.dest(distStaticPath + '/font/'));
});

//css压缩
gulp.task('sass2Css', function (cb) {
// sass转成css压缩（一个页面对应一个scss文件）
var pipe = gulp.src([
    srcStaticPath + '/sass/page/*.scss'
  ]);
  if(env !== "production"){
    pipe=pipe.pipe(sourcemaps.init());
  }

  pipe=pipe.pipe(cached('sass-task')).pipe(sass())
  // pipe=pipe.pipe(sass())
  .pipe(minifycss())
  .pipe(autoprefixer({
    browsers: ['last 4 versions'],
    cascade: false,
    remove: true
  }));
  if(env !== "production"){
    pipe=pipe.pipe(sourcemaps.write('maps'));
  }
pipe.pipe(gulp.dest(distStaticPath + '/css/page'));

//只需要复制的插件样式文件
gulp.src([
    srcStaticPath + '/css/common/swiper.css',
    srcStaticPath + '/css/common/video-js.css',
    srcStaticPath + '/css/common/datepicker.min.css'
  ])
  .pipe(minifycss())
  .pipe(gulp.dest(distStaticPath + '/css/common'));

cb();
});

//css合并(公用的样式和插件样式)
gulp.task('concatBaseCss', function () {
return gulp.src([
    srcStaticPath + '/css/common/reset.scss',
    srcStaticPath + '/css/common/common.scss',
    srcStaticPath + '/css/common/header.scss',
    srcStaticPath + '/css/common/footer.scss'
  ])
  .pipe(sass())
  .pipe(concat('base.css'))
  .pipe(autoprefixer({
    browsers: ['last 4 versions'],
    cascade: false,
    remove: true
  }))
  .pipe(minifycss())
  .pipe(gulp.dest(distStaticPath + '/css/common'));
});
gulp.task('js-base-online',function(){
  env = 'online';
  gulp.start('concatBaseJs');
});
//js合并（公用的脚本和插件脚本）
gulp.task('concatBaseJs', function () {
  let files = [
    srcStaticPath + '/js/lib/require.js',
    srcStaticPath + '/js/lib/jquery.js',
    // srcStaticPath + '/js/lib/jquery-ui.js',
    srcStaticPath + '/js/lib/jquery-ui-autocomplete.js',
    srcStaticPath + '/js/config.js',
    srcStaticPath + '/js/lib/cookie.js',
    srcStaticPath + '/js/util.js',
    srcStaticPath + '/js/url.js',
    srcStaticPath + '/js/geoData.js',
    srcStaticPath + '/js/headerSearch.js',
    srcStaticPath + '/js/global.js'
  ]

  if (env === 'production') {
    files = [
      srcStaticPath + '/js/lib/require.js',
      srcStaticPath + '/js/lib/jquery.js',
      // srcStaticPath + '/js/lib/jquery-ui.js',
      srcStaticPath + '/js/lib/jquery-ui-autocomplete.js',
      srcStaticPath + '/js/config.production.js',
      srcStaticPath + '/js/lib/cookie.js',
      srcStaticPath + '/js/util.js',
      srcStaticPath + '/js/url.js',
      srcStaticPath + '/js/geoData.js',
      srcStaticPath + '/js/headerSearch.js',
      srcStaticPath + '/js/global.js'
    ]
  }
  if (env === 'online') {
    files = [
      srcStaticPath + '/js/lib/require.js',
      srcStaticPath + '/js/lib/jquery.js',
      // srcStaticPath + '/js/lib/jquery-ui.js',
      srcStaticPath + '/js/lib/jquery-ui-autocomplete.js',
      srcStaticPath + '/js/config.online.js',
      srcStaticPath + '/js/lib/cookie.js',
      srcStaticPath + '/js/util.js',
      srcStaticPath + '/js/url.js',
      srcStaticPath + '/js/geoData.js',
      srcStaticPath + '/js/headerSearch.js',
      srcStaticPath + '/js/global.js'
    ]
  }


  var temp = gulp.src(files)
    .pipe(remember('js-task'))
    .pipe(concat('base.js'));
  if(env === 'online'){
    temp = temp.pipe(uglify());
  }
  return temp.pipe(gulp.dest(distStaticPath + '/js/lib'));
});

//js压缩混淆
gulp.task('compressJs', function (cb) {
//（每个页面对应一个js文件）
var pipe = gulp.src([
  srcStaticPath + '/js/page/*.js'
]);

// if (env === 'production') {
//   pipe = pipe.pipe(uglify());
// }

pipe.pipe(gulp.dest(distStaticPath + '/js/page'));

//只需要复制的js插件
gulp.src([
    srcStaticPath + '/js/lib/swiper.js',
    srcStaticPath + '/js/lib/waterfall.js',
    srcStaticPath + '/js/lib/juicer.js',
    srcStaticPath + '/js/lib/swiper-scrollbar.js',
    srcStaticPath + '/js/lib/datepicker.js',
    srcStaticPath + '/js/lib/countdown.min.js',
    srcStaticPath + '/js/lib/lazyload.js',
    srcStaticPath + '/js/lib/jquery.mCustomScrollbar.concat.min.js',
    srcStaticPath + '/js/lib/echarts.common.min.js',
    srcStaticPath + '/js/lib/jquery.marquee.min.js',
    srcStaticPath + '/js/gg.js',
    srcStaticPath + '/js/lib/jingdianData.js',
	  srcStaticPath + '/js/lib/baiduSearch.js',
    srcStaticPath + '/js/lib/easydialog.min.js'
  ])
  .pipe(cached("js-task"))
  .pipe(uglify())
  .pipe(gulp.dest(distStaticPath + '/js/lib'));

  gulp.src([srcStaticPath + '/js/lib/video-js.js']).pipe(gulp.dest(distStaticPath + '/js/lib'));
cb();

});

gulp.task('js', ['compressJs', 'concatBaseJs']);
// gulp.task('js', ['compressJs']);

gulp.task('css', ['concatBaseCss', 'sass2Css']);
gulp.task('json', function(){
  gulp.src([srcStaticPath + '/json/*.json',srcStaticPath + '/json/*.js']).pipe(gulp.dest(distStaticPath + '/json'));
});
//监听文件改变
gulp.task('update', function () {

var isMatch = function (extention, path) { //匹配文件
  var reg = new RegExp('.*\.' + extention + '$');
  if (reg.test(path)) {
    return true;
  }
  return false;
};

var execute = function (extention, path, task) { //执行对应的任务
  var i = 0;
  if (Array.isArray(extention)) { //传递的是数组
    for (; i < extention.length; i++) {
      if (isMatch(extention[i], path)) {
        gulp.start(task);
        break;
      }
    }
  } else {
    if (isMatch(extention, path)) {
      gulp.start(task);
    }
  }
};
var arr = [{
    extention: 'js',
    task: 'js'
  },
  {
    extention: 'css',
    task: 'css'
  },
  {
    extention: 'html',
    task: 'html'
  },
  {
    extention: ['png', 'jpg', 'jpeg'],
    task: 'img'
  },
  {
    extention: 'json',
    task: 'json'
  }
];
gulp.watch('src/**/*', function (event) {
  var path = event.path;
  var i = 0;
  var item;
  for (; i < arr.length; i++) {
    item = arr[i];
    execute(item.extention, path, item.task);
  }
});
});

//开发环境
gulp.task('development', function () {
gulp.start('img', 'js', 'json', 'css', 'html', 'swf', 'svg', 'font', 'update');
});

//生产环境
gulp.task('production', ['clean'], function () {
gulp.start('img', 'js', 'json', 'css', 'html', 'swf', 'svg', 'font');
});


//开发环境加热更新
gulp.task('default', function () {
browserSync.init({
  server: {
    baseDir: './dist',
    index: "首页/index.html"
  },
  port: 5000
});

gulp.start('development', browserSync.reload);

});

//给js文件加上版本号
gulp.task('config', function () {

  if (env === 'production') {
    return gulp.src([srcStaticPath + '/js/config.js'])
    .pipe(replace(/"(.*)\?version=(.*)"/g, function (match, p0, p1, offset, string) {
      var path = srcStaticPath + '/js/' + p0;
      var content = fs.readFileSync(path);
      var sign = md5(content);
      return '"' + p0 + '?version=' + sign + '"';
    }))
    .pipe(gulp.dest(srcStaticPath + '/js'));
  }else{
    return gulp.src([srcStaticPath + '/js/config.js'])
    .pipe(replace(/"(.*)\?version=(.*)"/g, function (match, p0, p1, offset, string) {
      var path = srcStaticPath + '/js/' + p0;
      var content = fs.readFileSync(path);
      var sign = md5(content);
      return '"' + p0 + '?version=' + sign + '"';
    }))
    .pipe(gulp.dest(srcStaticPath + '/js'));
  }

});

//生产打包
gulp.task('build', ['config'], function () {
env = 'production';
gulp.start('production');

});

// move
gulp.task('move', function () {
return gulp.src(
  './dist/static/**'
).pipe(gulp.dest('../static'));
});

// 给设计打包审核
gulp.task('sjbuild', ['config'], function () {
  gulp.start('production');
});